/*
 * GStreamer
 * Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
 * Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
 * Copyright (C) 2010 Wolfgang Breyha <wolfgang.breyha@univie.ac.at>
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 * Alternatively, the contents of this file may be used under the
 * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
 * which case the following provisions apply instead of the ones
 * mentioned above:
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/**
 * SECTION:element-v2esrc
 *
 * FIXME:Capture Source for Epiphan VGA2Ethernet
 *
 * <refsect2>
 * <title>Example launch line</title>
 * |[
 * gst-launch -v -m v2esrc ! 'video/x-raw-yuv,framerate=25/1,width=1024,height=768,format=(fourcc)I420' ! xvimagesink
 * ]|
 * </refsect2>
 */

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <gst/gst.h>

#include "gstv2esrc.h"
#include "v2esrc.h"

#include <string.h>
#include <stdlib.h>

GST_DEBUG_CATEGORY (gst_v2esrc_debug);
#define GST_CAT_DEFAULT gst_v2esrc_debug

enum
{
  PROP_0,
  PROP_HOST,
  PROP_FPS,
  PROP_CROPX,
  PROP_CROPY,
  PROP_CROPW,
  PROP_CROPH,
  PROP_HSHIFT,
  PROP_VSHIFT,
  PROP_PHASE,
  PROP_GAIN,
  PROP_OFFSET,
  PROP_PLLSHIFT,
  PROP_PREFWIDE,
  PROP_LAST
};

GST_BOILERPLATE (Gstv2esrc, gst_v2esrc, GstPushSrc,
    GST_TYPE_PUSH_SRC);

static void gst_v2esrc_finalize (GObject * gobject);

static void gst_v2esrc_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec);
static void gst_v2esrc_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec);

static GstCaps *gst_v2esrc_getcaps (GstBaseSrc * bsrc);
static gboolean gst_v2esrc_setcaps (GstBaseSrc * bsrc, GstCaps * caps);
static void gst_v2esrc_fixate (GstBaseSrc * bsrc, GstCaps * caps);

static gboolean gst_v2esrc_is_seekable (GstBaseSrc * psrc);
static gboolean gst_v2esrc_query (GstBaseSrc * bsrc, GstQuery * query);

static void gst_v2esrc_get_times (GstBaseSrc * basesrc,
    GstBuffer * buffer, GstClockTime * start, GstClockTime * end);
static GstFlowReturn gst_v2esrc_create (GstPushSrc * psrc,
    GstBuffer ** buffer);
static gboolean gst_v2esrc_start (GstBaseSrc * basesrc);
static gboolean gst_v2esrc_stop (GstBaseSrc * basesrc);

/* GObject vmethod implementations */

static void
gst_v2esrc_base_init (gpointer gclass)
{
  GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);

  gst_element_class_set_details_simple(element_class,
    "Video (VGA2Ethernet/raw) Source",
    "Source/Video",
    "Epiphan VGA2Ethernet Source",
    "Wolfgang Breyha <wolfgang.breyha@univie.ac.at>");

  gst_element_class_add_pad_template (element_class,
      gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
          gst_v2esrc_getcaps (NULL)));
}

/* initialize the v2esrc's class */
static void
gst_v2esrc_class_init (Gstv2esrcClass * klass)
{
  GObjectClass *gobject_class;
  GstBaseSrcClass *gstbasesrc_class;
  GstPushSrcClass *gstpushsrc_class;

  gobject_class = (GObjectClass *) klass;
  gstbasesrc_class = (GstBaseSrcClass *) klass;
  gstpushsrc_class = (GstPushSrcClass *) klass;

  gobject_class->set_property = gst_v2esrc_set_property;
  gobject_class->get_property = gst_v2esrc_get_property;
  gobject_class->finalize = gst_v2esrc_finalize;

  g_object_class_install_property (gobject_class, PROP_HOST,
      g_param_spec_string ("host", "Host", "The hostname/IP to connect to",
          V2E_DEFAULT_HOST, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_FPS,
      g_param_spec_double ("fps", "FPS",
          "maximum fps the framegrabber should provide",
          0.0, 120.0, 25.0,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_CROPX,
      g_param_spec_int ("cropx", "Crop X",
          "X offset of crop window",
          0, 4096, 0,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_CROPY,
      g_param_spec_int ("cropy", "Crop Y",
          "Y offset of crop window",
          0, 4096, 0,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_CROPW,
      g_param_spec_int ("cropw", "Crop Width",
          "width of crop window",
          -1, 4096, -1,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_CROPH,
      g_param_spec_int ("croph", "Crop Height",
          "height of crop window",
          -1, 4096, -1,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_HSHIFT,
      g_param_spec_int ("hshift", "Hshift",
          "Shifts image left (<0) or right(>0)",
          -999, 999 , 0,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_VSHIFT,
      g_param_spec_int ("vshift", "Vshift",
          "Shifts image down (<0) or up(>0)",
          -20, 20 , 0,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_PHASE,
      g_param_spec_int ("phase", "Phase",
          "Pixel sampling phase",
          V2U_MIN_PHASE, V2U_MAX_PHASE, 0,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_GAIN,
      g_param_spec_int ("gain", "Gain",
          "Gain for all colorchannels",
          V2U_MIN_GAIN, V2U_MAX_GAIN, 120,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_OFFSET,
      g_param_spec_int ("offset", "Offset",
          "Offset for all colorchannels",
          V2U_MIN_OFFSET, V2U_MAX_OFFSET, 63,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_PLLSHIFT,
      g_param_spec_int ("pllshift", "PLLShift", 
          "Adjusts the PLL value",
          -999, 999, 0,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_PREFWIDE,
      g_param_spec_boolean ("prefer-wide", "Prefer wide",
          "Sometimes 4:3 and wide modes with the same height are indistinguishable, "
          "so this flag can force choosing wide mode",
          0,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  gstbasesrc_class->get_caps = gst_v2esrc_getcaps;
  gstbasesrc_class->set_caps = gst_v2esrc_setcaps;
  gstbasesrc_class->is_seekable = gst_v2esrc_is_seekable;
  gstbasesrc_class->fixate = gst_v2esrc_fixate;
  gstbasesrc_class->query = gst_v2esrc_query;
  gstbasesrc_class->get_times = gst_v2esrc_get_times;
  gstbasesrc_class->start = gst_v2esrc_start;
  gstbasesrc_class->stop = gst_v2esrc_stop;

  gstpushsrc_class->create = gst_v2esrc_create;
}

/* initialize the new element
 * instantiate pads and add them to element
 * set pad calback functions
 * initialize instance structure
 */
static void
gst_v2esrc_init (Gstv2esrc * src,
    Gstv2esrcClass * gclass)
{
  GST_DEBUG_OBJECT (src, "init");
  src->fg_host = g_strdup (V2E_DEFAULT_HOST);
  src->fg_grabparam = g_malloc(sizeof(V2U_GrabParameters));
  src->ovrd_grabparam = g_malloc(sizeof(V2U_GrabParameters));
  src->ovrd_grabparam->flags &= 0;
  src->ovrd_grabparam->grab_flags &= 0;
  src->ovrd_grabparam->grab_flags_mask &= 0;
  src->cropw = -1;
  src->croph = -1;

  gst_base_src_set_format (GST_BASE_SRC (src), GST_FORMAT_TIME);
  gst_base_src_set_live (GST_BASE_SRC (src), 1);
}

static void
gst_v2esrc_fixate (GstBaseSrc * bsrc, GstCaps * caps)
{
  GstStructure *structure;
  Gstv2esrc *src = GST_V2ESRC (bsrc);
  int targetw, targeth;
  int i;

  GST_DEBUG_OBJECT (src, "fixate");
  structure = gst_caps_get_structure (caps, 0);

  /* do we have a FG connection? */
  if (src->fg)
  {
	GST_DEBUG_OBJECT (src, "device reported %dx%d", src->vmwidth, src->vmheight);
	targetw = src->vmwidth;
	targeth = src->vmheight;
	if ((src->cropw != -1) && (src->croph != -1))
	{
		targetw = src->cropw - src->cropx;
		targeth = src->croph - src->cropy;
	}

	GST_DEBUG_OBJECT (src, "targetting %dx%d", targetw, targeth);

	for (i = 0; i < gst_caps_get_size (caps); ++i) {
		structure = gst_caps_get_structure (caps, i);
		gst_structure_fixate_field_nearest_int (structure, "width", targetw);
		gst_structure_fixate_field_nearest_int (structure, "height", targeth);
		// gst_structure_fixate_field_nearest_fraction (structure, "framerate", 15, 2);
	}
  }
}

static void
gst_v2esrc_finalize (GObject * gobject)
{
  Gstv2esrc *src = GST_V2ESRC (gobject);

  GST_DEBUG_OBJECT (src, "finalize");
  v2e_deinit(src);
  g_free (src->fg_host);
  if (src->fg_grabparam)
  	g_free (src->fg_grabparam);
  if (src->ovrd_grabparam)
  	g_free (src->ovrd_grabparam);

  G_OBJECT_CLASS (parent_class)->finalize (gobject);
}


static void
gst_v2esrc_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec)
{
  Gstv2esrc *src = GST_V2ESRC (object);

  GST_DEBUG_OBJECT (src, "set_property");
  switch (prop_id) {
    case PROP_HOST:
      if (!g_value_get_string (value)) {
        g_warning ("host property cannot be NULL");
        break;
      }
      g_free (src->fg_host);
      src->fg_host = g_strdup (g_value_get_string (value));
      break;
    case PROP_FPS:
      src->fps = g_value_get_double (value);
      break;
    case PROP_CROPX:
      src->cropx = g_value_get_int (value);
      break;
    case PROP_CROPY:
      src->cropy = g_value_get_int (value);
      break;
    case PROP_CROPW:
      src->cropw = g_value_get_int (value);
      break;
    case PROP_CROPH:
      src->croph = g_value_get_int (value);
      break;
    case PROP_HSHIFT:
      src->ovrd_grabparam->hshift = g_value_get_int (value);
      src->ovrd_grabparam->flags |= V2U_FLAG_VALID_HSHIFT;
      break;
    case PROP_VSHIFT:
      src->ovrd_grabparam->vshift = g_value_get_int (value);
      src->ovrd_grabparam->flags |= V2U_FLAG_VALID_VSHIFT;
      break;
    case PROP_PHASE:
      src->ovrd_grabparam->phase = g_value_get_int (value);
      src->ovrd_grabparam->flags |= V2U_FLAG_VALID_PHASE;
      break;
    case PROP_GAIN:
      src->ovrd_grabparam->gain_r = g_value_get_int (value);
      src->ovrd_grabparam->gain_g = g_value_get_int (value);
      src->ovrd_grabparam->gain_b = g_value_get_int (value);
      src->ovrd_grabparam->flags |= V2U_FLAG_VALID_OFFSETGAIN;
      break;
    case PROP_OFFSET:
      src->ovrd_grabparam->offset_r = g_value_get_int (value);
      src->ovrd_grabparam->offset_g = g_value_get_int (value);
      src->ovrd_grabparam->offset_b = g_value_get_int (value);
      src->ovrd_grabparam->flags |= V2U_FLAG_VALID_OFFSETGAIN;
      break;
    case PROP_PLLSHIFT:
      src->ovrd_grabparam->pllshift = g_value_get_int (value);
      src->ovrd_grabparam->flags |= V2U_FLAG_VALID_PLLSHIFT;
      break;
    case PROP_PREFWIDE:
      src->ovrd_grabparam->grab_flags |= (g_value_get_boolean (value)) ? V2U_GRAB_PREFER_WIDE_MODE : 0;
      src->ovrd_grabparam->grab_flags_mask |= (g_value_get_boolean (value)) ? V2U_GRAB_PREFER_WIDE_MODE : 0;
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_v2esrc_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec)
{
  Gstv2esrc *src = GST_V2ESRC (object);

  GST_DEBUG_OBJECT (src, "get_property");
  switch (prop_id) {
    case PROP_HOST:
      g_value_set_string (value, src->fg_host);
      break;
    case PROP_FPS:
      g_value_set_double (value, src->fps);
      break;
    case PROP_CROPX:
      g_value_set_int (value, src->cropx);
      break;
    case PROP_CROPY:
      g_value_set_int (value, src->cropy);
      break;
    case PROP_CROPW:
      g_value_set_int (value, src->cropw);
      break;
    case PROP_CROPH:
      g_value_set_int (value, src->croph);
      break;
    case PROP_HSHIFT:
      g_value_set_int (value, src->ovrd_grabparam->hshift);
      break;
    case PROP_VSHIFT:
      g_value_set_int (value, src->ovrd_grabparam->vshift);
      break;
    case PROP_PHASE:
      g_value_set_int (value, src->ovrd_grabparam->phase);
      break;
    case PROP_GAIN:
      g_value_set_int (value, src->ovrd_grabparam->gain_r);
      break;
    case PROP_OFFSET:
      g_value_set_int (value, src->ovrd_grabparam->offset_r);
      break;
    case PROP_PLLSHIFT:
      g_value_set_int (value, src->ovrd_grabparam->pllshift);
      break;
    case PROP_PREFWIDE:
      g_value_set_boolean (value, ((src->ovrd_grabparam->grab_flags & V2U_GRAB_PREFER_WIDE_MODE) != 0));
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

/* threadsafe because this gets called as the plugin is loaded */
static GstCaps *
gst_v2esrc_getcaps (GstBaseSrc * bsrc)
{
  static GstCaps *capslist = NULL;

  GST_DEBUG_OBJECT (bsrc, "get_caps");
  if (!capslist) {
    GstCaps *caps;
    GstStructure *structure;
    int i;

    caps = gst_caps_new_empty ();
    for (i = 0; i < n_fourccs; i++) {
      structure = caps_get_structure (fourcc_list + i);
      gst_structure_set (structure,
          "width", GST_TYPE_INT_RANGE, 1, G_MAXINT,
          "height", GST_TYPE_INT_RANGE, 1, G_MAXINT,
          "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, G_MAXINT, 1, NULL);
      gst_caps_append_structure (caps, structure);
    }

    capslist = caps;
  }

  return gst_caps_copy (capslist);
}

static gboolean
gst_v2esrc_parse_caps (const GstCaps * caps,
    gint * width, gint * height, gint * rate_numerator, gint * rate_denominator,
    struct fourcc_list_struct **fourcc)
{
  const GstStructure *structure;
  GstPadLinkReturn ret;
  const GValue *framerate;

  GST_DEBUG ("parse_caps");

  if (gst_caps_get_size (caps) < 1)
    return FALSE;

  structure = gst_caps_get_structure (caps, 0);

  if (!(*fourcc = caps_find_by_structure (structure)))
    goto unknown_format;

  ret = gst_structure_get_int (structure, "width", width);
  ret &= gst_structure_get_int (structure, "height", height);
  framerate = gst_structure_get_value (structure, "framerate");

  if (framerate) {
    *rate_numerator = gst_value_get_fraction_numerator (framerate);
    *rate_denominator = gst_value_get_fraction_denominator (framerate);
  } else
    goto no_framerate;

  return ret;

  /* ERRORS */
unknown_format:
  {
    GST_DEBUG ("videotestsrc format not found");
    return FALSE;
  }
no_framerate:
  {
    GST_DEBUG ("videotestsrc no framerate given");
    return FALSE;
  }
}

static gboolean
gst_v2esrc_setcaps (GstBaseSrc * bsrc, GstCaps * caps)
{
  gboolean res;
  gint width, height, rate_denominator, rate_numerator;
  struct fourcc_list_struct *fourcc;
  Gstv2esrc *v2esrc;

  v2esrc = GST_V2ESRC (bsrc);

  GST_DEBUG_OBJECT (bsrc, "setcaps");
  res = gst_v2esrc_parse_caps (caps, &width, &height,
      &rate_numerator, &rate_denominator, &fourcc);
  if (res) {
    /* looks ok here */
    v2esrc->width = width;
    v2esrc->height = height;
    v2esrc->rate_numerator = rate_numerator;
    v2esrc->rate_denominator = rate_denominator;
    v2esrc->fourcc = fourcc;
    if (fourcc == NULL)
	return FALSE;
    v2esrc->fg_format = v2esrc->fourcc->v2eformat;
    v2esrc->bpp = v2esrc->fourcc->bitspp;

    GST_DEBUG_OBJECT (v2esrc, "size %dx%d, %d/%d fps, format: %x",
        v2esrc->width, v2esrc->height,
        v2esrc->rate_numerator, v2esrc->rate_denominator, v2esrc->fg_format);
  }
  return res;
}

static gboolean
gst_v2esrc_query (GstBaseSrc * bsrc, GstQuery * query)
{
  gboolean res;
  Gstv2esrc *src;

  src = GST_V2ESRC (bsrc);

  GST_DEBUG_OBJECT (src, "query");
  switch (GST_QUERY_TYPE (query)) {
    case GST_QUERY_CONVERT:
    {
      GstFormat src_fmt, dest_fmt;
      gint64 src_val, dest_val;

      gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
      if (src_fmt == dest_fmt) {
        dest_val = src_val;
        goto done;
      }

      switch (src_fmt) {
        case GST_FORMAT_DEFAULT:
          switch (dest_fmt) {
            case GST_FORMAT_TIME:
              /* frames to time */
              if (src->rate_numerator) {
                dest_val = gst_util_uint64_scale (src_val,
                    src->rate_denominator * GST_SECOND, src->rate_numerator);
              } else {
                dest_val = 0;
              }
              break;
            default:
              goto error;
          }
          break;
        case GST_FORMAT_TIME:
          switch (dest_fmt) {
            case GST_FORMAT_DEFAULT:
              /* time to frames */
              if (src->rate_numerator) {
                dest_val = gst_util_uint64_scale (src_val,
                    src->rate_numerator, src->rate_denominator * GST_SECOND);
              } else {
                dest_val = 0;
              }
              break;
            default:
              goto error;
          }
          break;
        default:
          goto error;
      }
    done:
      gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
      res = TRUE;
      break;
    }
    default:
      res = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
  }
  return res;

  /* ERROR */
error:
  {
    GST_DEBUG_OBJECT (src, "query failed");
    return FALSE;
  }
}

static gboolean
gst_v2esrc_is_seekable (GstBaseSrc * psrc)
{
  GST_DEBUG_OBJECT (psrc, "is_seekable");
  /* we're not seekable... */
  return FALSE;
}

static void
gst_v2esrc_get_times (GstBaseSrc * basesrc, GstBuffer * buffer,
    GstClockTime * start, GstClockTime * end)
{
  GST_DEBUG_OBJECT (basesrc, "get_times");
  /* for live sources, sync on the timestamp of the buffer */
  if (gst_base_src_is_live (basesrc)) {
    GstClockTime timestamp = GST_BUFFER_TIMESTAMP (buffer);

    if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
      /* get duration to calculate end time */
      GstClockTime duration = GST_BUFFER_DURATION (buffer);

      if (GST_CLOCK_TIME_IS_VALID (duration)) {
        *end = timestamp + duration;
      }
      *start = timestamp;
    }
  } else {
    *start = -1;
    *end = -1;
  }
}

static GstFlowReturn
gst_v2esrc_create (GstPushSrc * psrc, GstBuffer ** buffer)
{
  Gstv2esrc *src;
  GstBuffer *outbuf = NULL;
  GstClockTime next_time;

  src = GST_V2ESRC (psrc);

  if (G_UNLIKELY (src->fourcc == NULL))
    goto not_negotiated;

  /* 0 framerate and we are at the second frame, eos */
  if (G_UNLIKELY (src->rate_numerator == 0 && src->n_frames == 1))
    goto eos;

  GST_LOG_OBJECT (src,
      "creating buffer with %dx%d image for frame %d", 
      src->width, src->height, (gint) src->n_frames);

  outbuf = gst_buffer_new();
  gst_buffer_set_caps (outbuf, GST_PAD_CAPS (GST_BASE_SRC_PAD (psrc)));

  v2e_grab_image (src, outbuf, src->width, src->height);

  GST_BUFFER_TIMESTAMP (outbuf) = src->timestamp_offset + src->running_time;
  GST_BUFFER_OFFSET (outbuf) = src->n_frames;
  src->n_frames++;
  GST_BUFFER_OFFSET_END (outbuf) = src->n_frames;
  if (src->rate_numerator) {
    next_time = gst_util_uint64_scale_int (src->n_frames * GST_SECOND,
        src->rate_denominator, src->rate_numerator);
    GST_BUFFER_DURATION (outbuf) = next_time - src->running_time;
  } else {
    next_time = src->timestamp_offset;
    /* NONE means forever */
    GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
  }

  src->running_time = next_time;

  *buffer = outbuf;

  return GST_FLOW_OK;

not_negotiated:
  {
    GST_ELEMENT_ERROR (src, CORE, NEGOTIATION, (NULL),
        ("format wasn't negotiated before get function"));
    return GST_FLOW_NOT_NEGOTIATED;
  }
eos:
  {
    GST_DEBUG_OBJECT (src, "eos: 0 framerate, frame %d", (gint) src->n_frames);
    return GST_FLOW_UNEXPECTED;
  }
}

static gboolean
gst_v2esrc_start (GstBaseSrc * basesrc)
{
  Gstv2esrc *src = GST_V2ESRC (basesrc);
  int rc;

  GST_DEBUG_OBJECT (basesrc, "start");
  src->running_time = 0;
  src->n_frames = 0;

  v2e_init(src);
  rc = v2e_start(src);

  return rc;
}

static gboolean
gst_v2esrc_stop (GstBaseSrc * basesrc)
{
  Gstv2esrc *src = GST_V2ESRC (basesrc);

  GST_DEBUG_OBJECT (basesrc, "stop");
  src->running_time = 0;
  src->n_frames = 0;

  v2e_stop(src);

  return TRUE;
}

/* entry point to initialize the plug-in
 * initialize the plug-in itself
 * register the element factories and other features
 */
static gboolean
v2esrc_init (GstPlugin * v2esrc)
{
  /* debug category for fltering log messages
   *
   * exchange the string 'Template v2esrc' with your description
   */
  GST_DEBUG_CATEGORY_INIT (gst_v2esrc_debug, "v2esrc",
      0, "Epiphan VGA2Ethernet Source");

  return gst_element_register (v2esrc, "v2esrc", GST_RANK_NONE,
      GST_TYPE_V2ESRC);
}

/* PACKAGE: this is usually set by autotools depending on some _INIT macro
 * in configure.ac and then written into and defined in config.h, but we can
 * just set it ourselves here in case someone doesn't use autotools to
 * compile this code. GST_PLUGIN_DEFINE needs PACKAGE to be defined.
 */
#ifndef PACKAGE
#define PACKAGE "v2esrc"
#endif

/* gstreamer looks for this structure to register v2esrcs
 *
 * exchange the string 'Template v2esrc' with your v2esrc description
 */
GST_PLUGIN_DEFINE (
    GST_VERSION_MAJOR,
    GST_VERSION_MINOR,
    "v2esrc",
    "Epiphan VGA2Ethernet Source",
    v2esrc_init,
    VERSION,
    "LGPL",
    "GStreamer",
    "http://gstreamer.net/"
)
